package cn.imusic.discovery.registry.impl;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.inject.Singleton;

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import com.google.inject.ProvidedBy;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.appinfo.MyDataCenterInstanceConfig;
import com.netflix.appinfo.providers.MyDataCenterInstanceConfigProvider;

@Singleton
@ProvidedBy(MyDataCenterInstanceConfigProvider.class)
public class ImusicDataCenterInstanceConfig extends MyDataCenterInstanceConfig
    implements EnvironmentAware {

  private boolean preferIpAddress;
  
  private String instanceId;
  
  private Environment environment;

  /**
   * Initial status to register with rmeote Eureka server.
   */
  private InstanceStatus initialStatus = InstanceStatus.UP;

  public ImusicDataCenterInstanceConfig(boolean preferIpAddress) {

    this.preferIpAddress = preferIpAddress;
  }

  public ImusicDataCenterInstanceConfig(String namespace) {
    super(namespace);
  }

  public ImusicDataCenterInstanceConfig(String namespace, DataCenterInfo dataCenterInfo) {
    super(namespace, dataCenterInfo);
  }

  public String getInstanceId() {
    if (preferIpAddress) {
      return getIpAddress()+":"+getNonSecurePort();
    }
    return instanceId;
  }

  public void setInstanceId(String instanceId) {
    this.instanceId = instanceId;
  }

  @Override
  public String getHostName(boolean refresh) {
    if (preferIpAddress) {
      return getIpAddress();
    }
    return super.getHostName(refresh);
  }

  @Override
  public String getIpAddress() {
    try {
      return InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return super.getIpAddress();
  }

  public InstanceStatus getInitialStatus() {
    return this.initialStatus;
  }

  @Override
  public void setEnvironment(Environment environment) {
      this.environment = environment;
  }

  public Environment getEnvironment() {
    return environment;
  }

  public void setInitialStatus(InstanceStatus initialStatus) {
    this.initialStatus = initialStatus;
  }

}
